// pages/questions/index.js
const api = require('../../utils/api')
const util = require('../../utils/util')
const app = getApp()
let timer = null //计时器

Page({

    /**
     * 页面的初始数据
     */
    data: {
        user: '',
        account: '',
        wasteTime: null, //答题规定时间
        wasteTimeText: null, //答题规定时间（用于页面渲染）
        questionList: [], //题目数组
        currentIndex: 0, //当前题号
        singleOptionIndex: -1, //当前选项（单选）
        userArray: [], //多选时用户选择答案的数组
    },
    /**
     * 倒计时
     */
    Countdown: function () {
        timer = setInterval(() => {

            if (parseInt(this.data.wasteTimeText) < 1) {
                clearInterval(timer)
                this.errorHandle() //计时器结束未答题，作答错处理
                return
            }
            --this.data.wasteTimeText
            this.setData({
                wasteTimeText: this.data.wasteTimeText,
            })

        }, 1000)
    },
    /**
     * 比较数组是否相同
     */
    equalArray: function (arr1, arr2) {
        for (let i = 0; i < arr2.length; i++) {
            if (arr1.indexOf(arr2[i]) === -1) {
                return false
            }
        }
        return true
    },
    /**
     * 升星/降星
     * @param upStar 1.升星 2.降星
     * @rankType 排位赛类型 knowledge:知识排位 qualify:资质排位
     * @needback 是否携带返回操作
     */
    upstateStarApi: function (upStar) {

        let type = app.globalData.rankType,
            as = []
        //组装答案数组
        this.data.questionList.map(value => {
            as.push(value.answer)
        })
        switch (type) {
            case 'knowledge':
                api.post('/knowledge/updateKnowledgeRank', {
                    upStar,
                    as,
                }).
                then(res => {
                    switch (upStar) {
                        case 1:
                            console.log('升星成功')
                            api.showModalPromisified({
                                    title: '恭喜，升星成功',
                                    content: `继续挑战获取更多星星吧`,
                                    confirmColor: '#d56f47',
                                    cancelColor: '#999',
                                    showCancel: false
                                })
                                .then(res => {
                                    wx.navigateBack({
                                        delta: 1
                                    })
                                })
                            break;
                        case -1:
                            console.log('降星成功')
                            wx.navigateBack({
                                delta: 1
                            })
                            break;
                    }

                })
                break;
            case 'qualify':
                api.post('/qualify/updateQualifyRank', {
                    upStar,
                    as,
                }).
                then(res => {
                    switch (upStar) {
                        case 1:
                            console.log('升星成功')
                            api.showModalPromisified({
                                    title: '恭喜，升星成功',
                                    content: `继续挑战获取更多星星吧`,
                                    confirmColor: '#d56f47',
                                    cancelColor: '#999',
                                    showCancel: false
                                })
                                .then(res => {
                                    wx.navigateBack({
                                        delta: 1
                                    })
                                })
                            break;
                        case -1:
                            console.log('降星成功')
                            wx.navigateBack({
                                delta: 1
                            })
                            break;
                    }
                })
                break;
        }
    },
    /**
     * 正误验证
     */
    checkAnswer: function (answerArr, userArr) {
        clearInterval(timer)
        let bol = this.equalArray(answerArr, userArr)
        bol ? this.correctHandle() : this.errorHandle()
    },
    /**
     * 正确处理
     */
    correctHandle: function () {
        //最后一道题处理
        if (this.data.questionList.length === (this.data.currentIndex + 1)) {
            //post
            console.log('通知后台升星')
            this.upstateStarApi(1)
            return
        }
        this.data.currentIndex++
        this.setData({
            currentIndex: this.data.currentIndex,
            singleOptionIndex: -1,
            wasteTimeText: this.data.wasteTime
        })
        this.Countdown()
    },
    /**
     * 错误处理
     */
    errorHandle: function () {
        let account = wx.getStorageSync('account'),
            currentQuestion = this.data.questionList[this.data.currentIndex]

        //判断复活次数
        if (parseInt(account.frequency) < 1) {

            api.showModalPromisified({
                    title: '很遗憾，答错了',
                    content: `您今天的复活次数已用完，请明天再来`,
                    confirmColor: '#d56f47',
                    showCancel: false,
                    confirmText: '确定'
                })
                .then(() => {
                    console.log('复活次数用完返回,降星处理') //降星处理
                    this.upstateStarApi(-1)
                })
        } else {

            api.showModalPromisified({
                    title: '很遗憾，答错了',
                    content: `您今天还有${account.frequency}次复活机会，需要复活吗`,
                    confirmColor: '#d56f47',
                    cancelColor: '#999',
                    cancelText: '暂不复活',
                    confirmText: '立即复活'
                })
                .then(res => {

                    if (res.confirm) {

                        console.log('用户确定复活')
                        //请求复活接口
                        api.post('/user/wrongAnswer', {
                            date: Date.now()
                        }).
                        then(res => {
                            if (res.del === 0) return;
                            //减去本地复活次数
                            --account.frequency
                            console.log(account)
                            wx.setStorageSync('account', account)
                            //重置计时器和重置选项未选中
                            currentQuestion.selection.map(value => {
                                value.isSelect = false
                            })
                            this.setData({
                                singleOptionIndex: -1,
                                questionList: this.data.questionList,
                                userArray: [],
                                wasteTimeText: this.data.wasteTime
                            })
                            this.Countdown()
                        })

                    } else if (res.cancel) {
                        console.log('用户取消复活，通知后台降星')
                        this.upstateStarApi(-1)
                    }
                })
        }

    },
    /**
     * 单选
     */
    singleSelect: function (e) {
        let index = e.currentTarget.dataset.index,
            item = e.currentTarget.dataset.item,
            currentQuestion = this.data.questionList[this.data.currentIndex],
            answerArray = [],
            userArray = []
        this.setData({
            singleOptionIndex: index,
        })
        answerArray.push(currentQuestion.answer)
        userArray.push(item.option)
        this.checkAnswer(answerArray, userArray)

    },
    /**
     * 多选
     */
    multipleSelect: function (e) {
        let index = e.currentTarget.dataset.index,
            item = e.currentTarget.dataset.item,
            currentQuestion = this.data.questionList[this.data.currentIndex],
            answerArray = currentQuestion.answer.split(',')

        if (answerArray.length <= this.data.userArray.length) return;
        currentQuestion.selection[index].isSelect = currentQuestion.selection[index].isSelect ? false : true //选中和取消
        currentQuestion.selection[index].isSelect ? this.data.userArray.push(item.option) : this.data.userArray.splice(this.data.userArray.indexOf(item.option), 1) //用户选择或者取消答案

        this.setData({
            questionList: this.data.questionList,
            userArray: this.data.userArray
        })

        //根据多选答案个数进行验证正误
        if (answerArray.length === this.data.userArray.length) {
            this.checkAnswer(answerArray, this.data.userArray)
        }

    },
    /**
     * 生命周期函数--监听页面加载
     */
    onLoad: function (options) {

        app.globalData.testing = true //正在答题中

        let user = wx.getStorageSync('user'),
            account = wx.getStorageSync('account'),
            item = app.globalData.rankListItem
        this.setData({
            user,
            account
        })

        //请求随机题库
        let pageSize = parseInt(item.frequency || 0),
            Lv = parseInt(item.QbankLv || 0)
        api.post('/QBank/randomQBank', {
            pageSize,
            Lv,
        }).
        then(res => {

            //组装选项数据
            res.data.map((value, index) => {
                value.selection = []
                for (let p in value) {
                    if (/(opt)/.test(p) && value[p]) {
                        value.selection.push({
                            option: p,
                            answer: value[p],
                            isSelect: false
                        })
                    }
                }
            })

            this.setData({
                wasteTime: 10 || item.wasteTime,
                wasteTimeText: 10 || item.wasteTime,
                questionList: res.data
            })
            this.Countdown() //开始计时
        })

    },

    /**
     * 生命周期函数--监听页面初次渲染完成
     */
    onReady: function () {},

    /**
     * 生命周期函数--监听页面显示
     */
    onShow: function () {

    },

    /**
     * 生命周期函数--监听页面隐藏
     */
    onHide: function () {

    },

    /**
     * 生命周期函数--监听页面卸载
     */
    onUnload: function () {
        clearInterval(timer)
    },

    /**
     * 页面相关事件处理函数--监听用户下拉动作
     */
    onPullDownRefresh: function () {

    },

    /**
     * 页面上拉触底事件的处理函数
     */
    onReachBottom: function () {

    },

    /**
     * 用户点击右上角分享
     */
    onShareAppMessage: function () {

    }
})